<template>
  <el-dialog
    :visible.sync="dialogVisible"
    :before-close="handleClose"
    :close-on-click-modal="false"
    :title="`${$t('add')}`"
    width="75%">
    <el-row :gutter="40">
      <el-col :span="6">
        <el-card shadow="never" style="padding: 5px">
          <el-input
            v-model="filterText"
            :placeholder="`${$t('searchKeyword')}`"
          />
          <el-tree
            ref="tree"
            :props="treeProps"
            :data="treeData"
            :load="loadNode"
            :filter-node-method="filterNode"
            node-key="id"
            lazy
            show-checkbox
            @check-change="handleCheckChange"/>
        </el-card>
      </el-col>
      <el-col :span="18">
        <dynForm
          ref="dataForm"
          :info-form="searchForm"
          :search-tags="searchTags"
          :select-list="selectList"
          :rules="rules"
          label-width="130px"/></el-col>
    </el-row>
    <span slot="footer" class="dialog-footer">
      <el-button icon="el-icon-circle-close" @click="handleClose">{{
        $t("cancel")
      }}</el-button>
      <el-button v-btnThrottle="doSave" type="primary" icon="el-icon-receiving">{{
        $t("save")
      }}</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { getPMFormList } from '@/api/eForm/eFormCheck'
import { getAllUserList } from '@/api/system/user'
import { getPMTypeNames } from '@/api/maintenance/typeManage'
import { doAdd, doUpdate, getEqpTypeList, getEqpModelList, getEqpListByModel } from '@/api/maintenance/planManage'
import { getEqpTypes, getEqpNameListBy } from '@/api/equipment/eqpbase'
import { betterTips } from '@/utils/notification'
export default {
  name: 'PlanForm',
  components: {},
  props: {},
  data() {
    return {
      dialogVisible: false,
      searchForm: { status: 1 },
      rules: {
        pmScheduleName: [
          { required: true, message: `${this.$t('pleaseInput')}${this.$t('MaintenancePlanName')}`, trigger: 'blur' }
        ],
        pmTypeId: [
          { required: true, message: `${this.$t('pleaseInput')}${this.$t('pmTypeName')}`, trigger: 'change' }
        ],
        eqpType: [
          { required: true, message: `${this.$t('pleaseInput')}${this.$t('equipmentType')}`, trigger: 'change' }
        ],
        eqpList: [{ required: true, message: `${this.$t('pleaseInput')}${this.$t('eqpName')}`, trigger: 'blur' }],
        nextPMTime: [{ required: true, message: `${this.$t('pleaseInput')}${this.$t('nextPMDate')}`, trigger: 'change' }],
        formId: [{ required: true, message: `${this.$t('pleaseInput')}${this.$t('Checklist')}`, trigger: 'change' }],
        notifyUserIdList: [{ required: true, message: `${this.$t('pleaseInput')}${this.$t('NotificationofuserIDlist')}`, trigger: 'blur' }],
        pmLeastTime: [{ required: true, message: `${this.$t('pleaseInput')}${this.$t('MinimummaintenanceTime')}`, trigger: 'blur' }],
        notifyAdvanceDays: [{ required: true, message: `${this.$t('pleaseInput')}${this.$t('NumberofdaysinAdvance')}`, trigger: 'blur' }],
        notifyAdvanceFrequences: [{ required: true, message: `${this.$t('pleaseInput')}${this.$t('FrequencyOfAdvanceNotice')}`, trigger: 'blur' }]
      },
      searchTags: [
        { label: this.$t('MaintenancePlanName'), prop: 'pmScheduleName', tag: 'DynInput', width: '45%' },
        { label: this.$t('pmTypeName'), prop: 'pmTypeId', tag: 'DynSelect', width: '45%' },
        { label: this.$t('nextPMDate'), prop: 'nextPMTime', tag: 'Dyndate', width: '45%' },
        { label: this.$t('Checklist'), prop: 'formId', tag: 'DynSelect', width: '45%' },
        { label: this.$t('NotificationofuserIDlist'), prop: 'notifyUserIdList', tag: 'DynSelect', labelwidth: '150px', width: '45%', multiple: true },
        { label: this.$t('MinimummaintenanceTime'), prop: 'pmLeastTime', tag: 'DynInput', labelwidth: '150px', width: '45%' },
        { label: this.$t('NumberofdaysinAdvance'), prop: 'notifyAdvanceDays', tag: 'DynInput', width: '45%' },
        { label: this.$t('FrequencyOfAdvanceNotice'), prop: 'notifyAdvanceFrequences', tag: 'DynInput', labelwidth: '150px' },
        { label: this.$t('status'), prop: 'status', tag: 'DynSwitch', width: '100%' },
        { label: this.$t('remark'), prop: 'remark', tag: 'DynTextarea', row: 2, width: '100%' }
      ],
      selectList: {},
      filterText: '',
      treeProps: { label: 'name', isLeaf: 'leaf' },
      treeData: []
    }
  },
  computed: {},
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {},
  mounted() {},
  methods: {
    doSave() {
      this.$refs['dataForm'].$refs['dynForm'].validate((valid) => {
        if (valid) {
          if (this.searchForm.id) {
          // 根据后端接口需要需要进行转换
            doUpdate(this.searchForm).then(res => {
              betterTips(res, this.handleUpdate, this.handleClose)
            })
          } else {
            // 根据后端接口需要需要进行转换
            this.searchForm.notifyUserIdList = this.searchForm.notifyUserIdList.join(',')
            doAdd(this.searchForm).then(res => {
              betterTips(res, this.handleUpdate, this.handleClose)
            })
          }
        }
      })
    },
    loadNode(node, resolve) {
      switch (node.level) {
        case 1:
          getEqpModelList({ eqptype: node.data.id }).then(res => {
            resolve(res.data)
          })
          break
        case 2:
          getEqpListByModel({ eqpmodel: node.data.id }).then(res => {
            resolve(res.data)
          })
          break
        default:
          resolve([])
          break
      }
    },
    async handleCheckChange(data, resolve) {
      // doSomethings
      // console.log(data, resolve, '点击checkbox')
    },
    // 触发父组件更新
    handleUpdate() {
      this.$emit('initList')
    },
    handleOpen(val) {
      if (val && val.id) {
        // 暂定 这里应该需要调接口获取详情
        this.searchForm = Object.assign({}, val)
      }
      Promise.race([this.getPMFormList(),
        this.getUserList(),
        this.getPMTypeNamesList(),
        this.getEqpTypeList(),
        this.getEqpTypesList()])
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].$refs['dynForm'].clearValidate()
      })
    },
    handleClose() {
      Object.assign(this.$data, this.$options.data.call(this))
    },
    filterNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    // 设备类型->获取->设备名称
    async change(item, val) {
      if (item.change && val) {
        const res = await getEqpNameListBy({ EqpType: val })
        this.$set(this.selectList, 'eqpList', res.data)
      }
    },
    // 工号列表
    async getUserList() {
      const res = await getAllUserList()
      this.$set(this.selectList, 'notifyUserIdList', res.data)
    },
    // 检查表单
    async getPMFormList() {
      const res = await getPMFormList()
      this.$set(this.selectList, 'formId', res.data)
    },
    // 获取维保类型名称
    async getPMTypeNamesList() {
      const res = await getPMTypeNames()
      this.$set(this.selectList, 'pmTypeId', res.data)
    },
    // 获取设备型号
    async getEqpTypesList() {
      const res = await getEqpTypes()
      this.$set(this.selectList, 'eqpType', res.data)
    },
    // 获取所有的设备类型
    async getEqpTypeList() {
      const res = await getEqpTypeList()
      this.treeData = res.data
    }
  }
}
</script>

<style scoped lang="scss">
  ::v-deep .el-form-item{
      .el-form-item__content{
        .el-date-editor {
          width: 175px;
        }
      }
  }
  ::v-deep .el-form-item:last-child{
      .el-form-item__content{
        width: 60%;
      }
  }
</style>
